if (!window.dw) {
    var dw = {};
}
if (!window.dw.ImageUploader) {
    dw.ImageUploader = (function () {
        var defaults = {
            uploadURL : 'dynamic-resource',
            title : '头像上传',
            imagePath : 'dynamic-resource',
            imageFieldName : 'f',
            acceptTypes : {
                filter: /.*?\.(gif|jpeg|jpg|png)$/ig,
                display: '头像文件 (*.gif; *.jpg, *.jpeg, *.png)'
            },
            preview: true
        }, settings, file, panel, progress, component_panel, message_panel;

        function upload () {
            if (!checkData ()) {
                return;
            }

            component_panel.hide ();
            message_panel.show ();
            $(progress).show ();
            $('.upload-error-message').text ('正在上传文件' + file.value + '...');

            var xhr = new XMLHttpRequest ();
            var form = new FormData ();
            form.append ('f', file.files [0]);
            xhr.onload = function (response) {
                if (response.target.readyState == 4) {
                    var data = eval ('(' + response.target.responseText + ')');
                    if (data.status == 'ok') {
                        mask.hide (function () {
                            var item = data.items[0];
                            var src = settings ['imagePath'] + '?t=file&f=' + encodeURIComponent(item['name']);
                            var target = $(settings ['target']);
                            $('#iconPath').val (item['name']);
                            target.attr ('src', src);
                            $(panel).hide ();
                        });
                    } else {
                        $('.upload-error-message').text ('上传文件' + file.value + '失败');
                    }
                }
            };
            xhr.upload.addEventListener ('progress', function (event) {
                if (event ['lengthComputable']) {
                    progress.max = event['total'];
                    progress.value = event['loaded'];
                }
            }, false);
            xhr.open ('POST', settings ['uploadURL'], true);
            xhr.send (form);
        }

        function close () {
            $(panel).hide ();
            mask.hide ();
        }

        function checkData () {
            if (!settings.acceptTypes.filter.test (file.value)) {
                $('.upload-error-message').text ('不支持的文件类型');
                message_panel.show ();
                return false;
            }
            return true;
        }

        function createPanel () {
            var div = document.createElement ('div');
            var root = $(div).on ('click', function (event) {event.stopPropagation ();});
            div.className = 'image-uploader-root';
            $('<h1/>').appendTo (root).text (settings ['title']);

            component_panel = $('<div/>').appendTo (root);
            file = $('<input type="file" />').appendTo (component_panel)
                .attr ('name', 'f').css ('width', '100%').get (0);
            $('<div/>').text (settings.acceptTypes.display).appendTo (component_panel)
                .addClass ('tip-panel');

            message_panel = $('<div/>').appendTo (root);
            $(progress = document.createElement ('progress')).appendTo (message_panel)
                .css ({'width':'100%', display:'none'});
            $('<div/>').appendTo (message_panel).addClass ('upload-error-message');
            message_panel.hide ();
            var p = $('<div/>').appendTo (root).addClass ('button-panel');
            $('<a/>').appendTo (p).text ('确定').button ().on ('click', upload);
            $('<a/>').appendTo (p).text ('取消').button ().on ('click', function () {
                close ();
            });
            return div;
        }

        return {
            config : function (options) {
                settings = $.extend ({}, defaults, options || {});
                panel  = createPanel();
                $(document).on ('click', function () {close();});

                document.body.appendChild (panel);
                if (!settings ['target'])
                    throw 'setting::target is required!';
                var target = $(settings ['target']);
                target.addClass ('image-uploader-handler').on ('click', function (event) {
                    event.stopPropagation ();
                    mask.show (function () {
                        $(panel).show ();
                        message_panel.hide ();
                        component_panel.show ();
                        $(progress).hide ();
                        $('.upload-error-message').text ();
                        file.value = '';
                        var p = $(panel), w = $(window);
                        var x = (w.width () - p.width ()) / 2,
                            y = (w.height () - p.height ()) / 2;
                        $(panel).css ({top:y,left:x});
                    });
                });
            }
        };
    })();
}